package com.springboot.config.shiro;

import com.springboot.config.tool.ToolUtil;
import com.springboot.project.common.entity.User;
import com.springboot.project.common.service.impl.ModuleServiceImpl;
import com.springboot.project.common.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: lby.
 * Date: 2018/4/6.
 * Version: V1.0.
 */
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private ModuleServiceImpl moduleService;

    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.err.println("------执行登录认证------");
        //UsernamePasswordToken对象用来存放提交的登录信息
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;

        //查找是否存在用户
        String username = token.getUsername();
        User user = userService.getUserByName(username);
        if(user!=null){
            // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
            //return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        }
        return null;
    }

    /**
     * 权限认证，为当前登录的Subject授予角色和权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.err.println("------执行角色授权------");
        //User user=(User) principals.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
        User user=(User)SecurityUtils.getSubject().getPrincipal();
        List<Integer> roleList = ToolUtil.getRoleId(user.getRoleid());
        Set<String> permissionSet = new HashSet<>();
        Set<String> roleNameSet = new HashSet<>();

        for (Integer roleId : roleList) {
            List<String> permissions = moduleService.getPermissionsByRoleId(roleId);
            if (permissions != null) {
                for (String permission : permissions) {
                    if (ToolUtil.isNotEmpty(permission)) {
                        permissionSet.add(permission);
                    }
                }
            }
            //String roleName = ShiroTool.getRoleNameById(roleId);
            String roleName = userService.getRoleNameById(roleId);
            roleNameSet.add(roleName);
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissionSet);   //将权限放入shiro中.
        info.addRoles(roleNameSet);
        return info;
    }
}
